import { defaultRoute, asyncRoutes, constantRoutes } from '@/router'

import Layout from '@/layout'
import ModuleLayout from '@/layout/module'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

// 路由懒加载
const loadLayoutAsyncView = item => {
  if (!item.parent) {
    return Layout
  } else if (item.children && item.children.length > 0) {
    return ModuleLayout
  } else {
    return resolve => require([`@/views${item.template}`], resolve)
  }
}

const generateAsyncRoute = data => {
  return data.map(item => {
    var children =
      item.children && item.children.length > 0 ? generateAsyncRoute(item.children) : []
    var tempRoute = {
      path: item.path,
      component: loadLayoutAsyncView(item),
      hidden: item.hidden,
      children: children,
      name: item.name,
      meta: item.meta,
      redirect: item.redirect
    }
    return tempRoute
  })
}

const actions = {
  generateRoutes({ commit }, { roles, menus }) {
    return new Promise(resolve => {
      generateAuthTreeMenu(menus)
        .then(asyncRoutes => {
          let accessedRoutes
          if (roles.includes('admin')) {
            accessedRoutes = asyncRoutes || []
          } else {
            accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
          }
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
        .catch(error => {
          console.log(error)
        })
    })
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generateAuthTreeMenu(data) {
  return new Promise(resolve => {
    const routes = generateAsyncRoute(data)
    resolve([...asyncRoutes, ...routes, defaultRoute])
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
